package com.example.neuronview

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.CheckBox
import android.widget.TextView
import android.widget.Toast
// ViewHolder用于缓存视图组件

class SampleAdapter(val context: Context, val samples:MutableList<Sample>): BaseAdapter(){
    private lateinit var sampleid: String
    private lateinit var checkbox:  CheckBox
    private val inflater: LayoutInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
    override fun getCount(): Int {
        return samples.size
    }
    var onCheckBoxStateChanged:((position:Int,isChecked: Boolean,item:Sample)->Unit)?=null

    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View? {

        val view: View
        val viewHolder: ViewHolder

        if (convertView == null) {
            // 新建视图并创建ViewHolder
            view = LayoutInflater.from(context).inflate(R.layout.sampleitem, parent, false)
            viewHolder = ViewHolder()
            viewHolder.checkBox = view.findViewById(R.id.ckSampleid)
            view.tag = viewHolder // 将ViewHolder存储在View中
        } else {
            // 复用已有视图和ViewHolder
            view = convertView
            viewHolder = view.tag as ViewHolder
        }
        // 获取当前位置的数据
        val item = samples[position]

        // 取消之前的监听器，避免复用导致的问题
        viewHolder.checkBox.setOnCheckedChangeListener(null)

        // 根据数据设置复选框状态
        viewHolder.checkBox.isChecked = item.isSelected

        // 重新设置监听器
        viewHolder.checkBox.setOnCheckedChangeListener { _, isChecked ->
            // 更新数据模型中的状态
            item.isSelected = isChecked
            // 触发回调
            onCheckBoxStateChanged?.invoke(position, isChecked, item)
        }

        view.findViewById<TextView>(R.id.tvSampleid).text = item.sampleid
        view.findViewById<TextView>(R.id.tvPI).text = item.pi
        view.findViewById<TextView>(R.id.tvRegion).text= item.region.toString()
        return view
    }

    override fun getItem(position: Int): Any? {
        return samples[position]
    }

    override fun getItemId(position: Int): Long {
        return 0
    }
    private fun showToast(message: String) {
        Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
    }
}